﻿
<%@ WebHandler Language="C#" Class="OrganizationMgr" %>

using System;
using System.Text;
using System.Web;
using System.Data;
using System.Collections.Generic;
using Chenxin.Lib.Utility;

public class OrganizationMgr : AjaxHandlerBase
{
    public OrganizationMgr()
    {
        //部门删除
        htTypePermit.Add("del", Constants.Permit_NodeDel);
        //部门迁移
        htTypePermit.Add("move", Constants.Permit_NodeMove);
        //部门编辑
        htTypePermit.Add("edit", Constants.Permit_NodeEdit);
        //部门添加
        htTypePermit.Add("add", Constants.Permit_NodeAdd);
        //城市节点添加
        htTypePermit.Add("addcity", Constants.Permit_NodeAddCity);
        //公司节点添加
        htTypePermit.Add("addcompany", Constants.Permit_NodeAddCompany);
        //部门人员添加
        htTypePermit.Add("empsetting", Constants.Permit_UserInfoSet);
        //部门人员删除
        htTypePermit.Add("deluser", Constants.Permit_DepartUserDel);
        //密码重置
        htTypePermit.Add("resetpwd", Constants.Permit_PasswordReset);
        //业务所属地设置
        htTypePermit.Add("local", Constants.Permit_LocalSet);
        //默认部门业务设置
        htTypePermit.Add("settermssetting", Constants.Permit_TermsSet);
        //导出
        htTypePermit.Add("exportdata", Constants.Permit_OrganizationExport);
    }
    
    private Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
    
    
    public override void RequestProcess(HttpContext context)
    {
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        
        switch (context.Request["op"].ToLower())
        {
            case "gettree":     //得到组织结构树形
                GetTree(context);
                break;
            case "add":         //添加节点
                AddDep(context);
                break;
            case "addcity":         //添加城市节点
                AddDep(context);
                break;
            case "addcompany":         //添加公司节点
                AddDep(context);
                break;
            case "edit":        //编辑节点
                EditDep(context);
                break;
            case "del":         //删除节点
                DelDep(context);
                break;
            case "move":        //转移节点
                MoveDep(context);
                break;
            case "resetpwd":    //密码重置
                resetPassword(context);
                break;
            case "local":       //设置业务所属地
                setLocal(context);
                break;
            case "getuserbycode":       //员工工号验证
                getUserByCode(context);
                break;
            case "empsetting":         //添加人员业务权限
                addUser(context);
                break;
            case "deluser":         //删除人员业务权限
                delUser(context);
                break;
            case "getlist":    //得到部门中人员的业务数据
                getUsersInfo(context);
                break;
            case "checkname":       //验证名称
                NameCheck(context);
                break;
            case "checkcode":       //验证编号
                CodeCheck(context);
                break;
            case "getmodel":        //根据部门ID得到部门基本信息
                getDepartInfo(context);
                break;
            case "getsettingmodel":     //根据部门ID得到部门参数
                getDepartSetting(context);
                break;
            case "getrolebycompany":    //根据公司ID得到角色集
                GetRole(context);
                break;
            case "gettermssetting":     //得到部门业务设定
                GetTermsSetting(context);
                break;
            case "settermssetting":     //设置部门业务设定
                SetTermsSetting(context);
                break;
            case "getareausemodel":     //得到公司片区设定
                getareausemodel(context);
                break;
        }
    }
    
    //得到公司片区设定
    private void getareausemodel(HttpContext context)
    {
        try
        {
            string DepartId = context.Request.QueryString["modelid"];
            StringBuilder strb = new StringBuilder();

            string strKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPART_SETTINGS, DepartId);
            Chenxin.Lib.House.Entity.House_BusinessSetting ds;
            ds = cs.GetObject(strKey) as Chenxin.Lib.House.Entity.House_BusinessSetting;
            if (!cs.Hit || ds == null)
            {
                ds = Chenxin.Lib.House.DAL.House_BusinessSetting.GetModel(new Guid(DepartId));
                if (ds != null) cs.Set(strKey, ds);
            }
            if (ds==null)
            {
                ds = new Chenxin.Lib.House.Entity.House_BusinessSetting();
                ds.UseBlockRole=false;
                ds.BlockRoleNum = 0;
            }
            context.Response.Write(string.Format("{{success:1,msg:'',data:{{model:{{AreaUse:{0},AreaType:{1}}}}}}}",
                    ds.UseBlockRole.ToString().ToLower(),ds.BlockRoleNum.ToString()));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message));
        }
    }
    
    

    //得到部门参数
    private void getDepartSetting(HttpContext context)
    {
        try{
            string DepartId = context.Request.QueryString["modelid"];
            StringBuilder strb = new StringBuilder();

            string strKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPART_SETTINGS, DepartId);
            Chenxin.Lib.House.Entity.House_BusinessSetting ds;
            ds = cs.GetObject(strKey) as Chenxin.Lib.House.Entity.House_BusinessSetting;
            if (!cs.Hit || ds == null)
            {
                ds = Chenxin.Lib.House.DAL.House_BusinessSetting.GetModel(new Guid(DepartId));
                if (ds != null) cs.Set(strKey, ds);
            }
            context.Response.Write(string.Format("{{success:'1',msg:'成功',data:{{model:{0}}}}}",
                    Chenxin.Lib.Utility.JsonHelp.Convert2Json(ds)));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message));
        }
    }
    

    //根据部门ID得到部门业务设定
    private void GetTermsSetting(HttpContext context)
    {
        string depid = context.Request.QueryString["departid"];
        string terms = context.Request.QueryString["terms"];
        string strSql = string.Format("DepartID='{0}' and TermsName='{1}' ", depid, terms);
        List<Chenxin.Lib.Hr.Entity.HR_Rel_Purview> list = Chenxin.Lib.Hr.DAL.HR_Rel_Purview.GetListArray(strSql);
        if (list.Count > 0)
        {
            StringBuilder strb = new StringBuilder();
            //strb.Append("{success:'1',data:{");

            Chenxin.Lib.Hr.Entity.HR_Rel_Purview temp = list[0];
            if (temp.ViewPubHouse)
            {
                strb.Append("ViewPubHouse,");
            }

            if (temp.ViewPrivHouse)
            {
                strb.Append("ViewPrivHouse,");
            }
            if (temp.ViewHideHouse)
            {
                strb.Append("ViewHideHouse,");
            }
            //if (temp.ViewPubDemand)
            //{
            //    strb.Append("ViewPubDemand,");
            //}
            if (temp.ViewPrivDemand)
            {
                strb.Append("ViewPrivDemand,");
            }
            if (temp.ViewRealCustomer)
            {
                strb.Append("ViewRealCustomer,");
            }
            if (temp.ViewFakeCustomer)
            {
                strb.Append("ViewFakeCustomer,");
            }
            if (temp.EditPrimaryHouse)
            {
                strb.Append("EditPrimaryHouse,");
            }
            if (temp.EditNormalHouse)
            {
                strb.Append("EditNormalHouse,");
            }
            if (temp.DelTrace)
            {
                strb.Append("DelTrace,");
            }
            if (temp.CanProtect)
            {
                strb.Append("CanProtect,");
            }
            if (temp.CanLockHouse)
            {
                strb.Append("CanLockHouse,");
            }
            if (temp.ViewLockHouse)
            {
                strb.Append("ViewLockHouse,");
            }
            if (temp.ViewChange)
            {
                strb.Append("ViewChange,");
            }
            if (temp.CanChangeConfirm)
            {
                strb.Append("CanChangeConfirm,");
            }
            if (temp.ViewEntrust)
            {
                strb.Append("ViewEntrust,");
            }
            if (temp.CanCancelTrust)
            {
                strb.Append("CanCancelTrust,");
            }
            if (temp.UnCancelTrust)
            {
                strb.Append("UnCancelTrust,");
            }
            if (temp.CanDelTrust)
            {
                strb.Append("CanDelTrust,");
            }
            if (temp.ViewWatching)
            {
                strb.Append("ViewWatching,");
            }
            if (temp.EditWatching)
            {
                strb.Append("EditWatching,");
            }
            if (temp.EditKey)
            {
                strb.Append("EditKey,");
            }
            if (temp.UseKey)
            {
                strb.Append("UseKey,");
            }
            if (temp.EditKeyUsing)
            {
                strb.Append("EditKeyUsing,");
            }
            if (temp.EditTrust)
            {
                strb.Append("EditTrust,");
            }
            if (temp.CancelLockHouse)
            {
                strb.Append("CancelLockHouse,");
            }
            //if (temp.ViewPubCustomer)
            //{
            //    strb.Append("ViewPubCustomer,");
            //}
            if (temp.ViewPrivCustomer)
            {
                strb.Append("ViewPrivCustomer,");
            }
            if (temp.EditPubDemand)
            {
                strb.Append("EditPubDemand,");
            }
            if (temp.EditPrivDemand)
            {
                strb.Append("EditPrivDemand,");
            }
            if (temp.ViewTelLog)
            {
                strb.Append("ViewTelLog,");
            }
            if (temp.ViewBusiness)
            {
                strb.Append("ViewBusiness,");
            }
            if (temp.ViewHrInfo)
            {
                strb.Append("ViewHrInfo,");
            }
            if (temp.ViewHrChange)
            {
                strb.Append("ViewHrChange,");
            }
            if (temp.ViewAttendance)
            {
                strb.Append("ViewAttendance,");
            }
            if (temp.ViewVacation)
            {
                strb.Append("ViewVacation,");
            }
            if (temp.ViewAnnualLeave)
            {
                strb.Append("ViewAnnualLeave,");
            }
            if (temp.ViewUserLog)
            {
                strb.Append("ViewUserLog,");
            }
            if (temp.DelHouse)
            {
                strb.Append("DelHouse,");
            }

            if (temp.EditPubCustomer)
            {
                strb.Append("EditPubCustomer,");
            }
            if (temp.EditPrivCustomer)
            {
                strb.Append("EditPrivCustomer,");
            }
            if (temp.ViewStock)
            {
                strb.Append("ViewStock,");
            }
            if (temp.IsControl)
            {
                strb.Append("IsControl,");
            }
            if (temp.ShiftPubCustomer)
            {
                strb.Append("ShiftPubCustomer,");
            }
            if (temp.SetPubLevel)
            {
                strb.Append("SetPubLevel,");
            }
            if (temp.ViewCrossPubShareDemand)
            {
                strb.Append("ViewCrossPubShareDemand,");
            }
            if (temp.ViewPubShareDemand)
            {
                strb.Append("ViewPubShareDemand,");
            }
            if (temp.ViewCrossPubShareCustomer)
            {
                strb.Append("ViewCrossPubShareCustomer,");
            }
            if (temp.ViewPubShareCustomer)
            {
                strb.Append("ViewPubShareCustomer,");
            }
            if (temp.ViewTrace)
            {
                strb.Append("ViewTrace,");
            }
            if (temp.CanUploadPicture)
            {
                strb.Append("CanUploadPicture,");
            }
            if (temp.CanDeletePicture)
            {
                strb.Append("CanDeletePicture,");
            }
            if (temp.CanPublishHouse)
            {
                strb.Append("CanPublishHouse,");
            }
            if (strb.Length > 0)
            {
                strb.Remove(strb.Length - 1, 1);
            }

            //strb.Append("}}");
            context.Response.Write(string.Format("{{success:1,msg:'',data:{{purview:'{0}'}}}}", strb.ToString()));
        }
        else
        {
            context.Response.Write("{success:'1',msg:'',data:{purview:''}}");
        }
    }

    /// <summary>
    /// 增加或更新部门业务设定
    /// </summary>
    /// <param name="context"></param>
    private void SetTermsSetting(HttpContext context)
    {
        string depid = context.Request.Params["departid"];
        string terms = context.Request.Params["terms"];
        string setting = "";
        string str_setting = "";
        if (!string.IsNullOrEmpty(context.Request.Params["purview"]))
        {
            setting = context.Request.Params["purview"];
            string[] array = setting.Split(',');
            for (int i = 0; i < array.Length; i++)
            {
                str_setting += "'1',";
            }
            str_setting = str_setting.Substring(0, (str_setting.Length - 1));
        }
        string strSql = "";
        strSql += string.Format("delete HR_Rel_Purview where DepartID='{0}' and TermsName='{1}';", depid, terms);
        strSql += string.Format("insert into HR_Rel_Purview(RecodID,DepartID,TermsName,{0},Addtime) values(newid(),'{1}','{2}',{3},getdate());", setting, depid, terms, str_setting);

        try
        {
            Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.ExecuteSQL(strSql);

            Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo dep = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(new Guid(depid));

            AddLog("" + CurrentUserInfo.UserName + "设置部门默认业务:部门姓名[" + dep.DepartName + "(" + dep.CompanyName + ")]",
                    OperationType.OperationTypeComboList()["OprType_SetDepBusiness"].ToString());
            
            context.Response.Write("{success:'1',msg:'设置成功！',data:''}");
        }
        catch (Exception ex)
        {
            context.Response.Write("{success:'0',msg:'" + ex.Message.Replace("'","\"") + "',data:''}");
        }
    }


    //根据用户工号得到用户信息
    private void GetUserByCode(HttpContext context)
    {
        try
        {
            string usercode = context.Request.QueryString["usercode"];
            Chenxin.Lib.Passport.Entity.Hr_UserInfo userinfo = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetEntityByCode(usercode);
            if (userinfo != null)
                context.Response.Write("{success:'1',msg:'',data:{UserName:'" + userinfo.UserName + "(" + userinfo.BelongDepart + ")',UserId:'" + userinfo.UserId + "'}}");
            else
                context.Response.Write("{success:'0',mst:'工号：" + usercode + "不存在！',data:''}");
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message));
        }
    }

    
    
    //根据公司ID得到角色数据
    private void GetRole(HttpContext context)
    {
        try
        {
            string companyid = context.Request.Params["companyid"];
            string strSql = string.Format("CompanyId='{0}'",companyid);
            
            List<Chenxin.Lib.Hr.Entity.Base_Permit_RoleDefine> list = Chenxin.Lib.Hr.DAL.Base_Permit_RoleDefine.GetListArray(strSql);
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            if (list.Count > 0)
            {
                foreach (Chenxin.Lib.Hr.Entity.Base_Permit_RoleDefine r in list)
                {
                    sb.AppendFormat("{{txt:'{0}',val:'{1}'}},", r.RoleName, r.RoleId);
                }
                sb.Remove(sb.Length - 1, 1);
            }
            context.Response.Write(string.Format("{{success:'1',msg:'',data:{{items:[{0}]}}}}", sb.ToString()));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message));
        }
    }
    

    //根据部门ID得到该部门的人员权限信息
    public void getUsersInfo(HttpContext context)
    {
        try
        {
            //参数列表
            int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数

            //order文
            string strOrder = "Struct_UserDepartRelation.IsBelong desc,Struct_UserDepartRelation.usercode desc";
            //查询表格
            string tablename = "Struct_UserDepartRelation";
            //select文
            string TableFieldList = "RecordId,UserCode,UserName,CASE WHEN IsBelong='1' THEN '√' ELSE '' END  AS IsBelong,CASE WHEN IsRoleA='1' THEN '√' ELSE '' END  AS IsRoleA,CASE WHEN IsRoleB='1' THEN '√' ELSE '' END  AS IsRoleB,CASE WHEN IsRoleC='1' THEN '√' ELSE '' END  AS IsRoleC,CASE WHEN IsRoleD='1' THEN '√' ELSE '' END  AS IsRoleD,CASE WHEN IsRoleE='1' THEN '√' ELSE '' END  AS IsRoleE,CASE WHEN IsRoleF='1' THEN '√' ELSE '' END  AS IsRoleF,CASE WHEN ViewPubHouse='1' THEN '√' ELSE '' END  AS ViewPubHouse,CASE WHEN ViewPrivHouse='1' THEN '√' ELSE '' END  AS ViewPrivHouse,CASE WHEN ViewHideHouse='1' THEN '√' ELSE '' END  AS ViewHideHouse,CASE WHEN ViewPrivDemand='1' THEN '√' ELSE '' END  AS ViewPrivDemand,CASE WHEN ViewRealCustomer='1' THEN '√' ELSE '' END  AS ViewRealCustomer,CASE WHEN ViewFakeCustomer='1' THEN '√' ELSE '' END  AS ViewFakeCustomer,CASE WHEN EditPrimaryHouse='1' THEN '√' ELSE '' END  AS EditPrimaryHouse,"
                + "CASE WHEN EditNormalHouse='1' THEN '√' ELSE '' END  AS EditNormalHouse,CASE WHEN DelTrace='1' THEN '√' ELSE '' END  AS DelTrace,CASE WHEN CanProtect='1' THEN '√' ELSE '' END  AS CanProtect,CASE WHEN CanLockHouse='1' THEN '√' ELSE '' END  AS CanLockHouse,CASE WHEN ViewLockHouse='1' THEN '√' ELSE '' END  AS ViewLockHouse,CASE WHEN ViewChange='1' THEN '√' ELSE '' END  AS ViewChange,CASE WHEN CanChangeConfirm='1' THEN '√' ELSE '' END  AS CanChangeConfirm,CASE WHEN ViewEntrust='1' THEN '√' ELSE '' END  AS ViewEntrust,CASE WHEN CanCancelTrust='1' THEN '√' ELSE '' END  AS CanCancelTrust,CASE WHEN UnCancelTrust='1' THEN '√' ELSE '' END  AS UnCancelTrust,CASE WHEN CanDelTrust='1' THEN '√' ELSE '' END  AS CanDelTrust,CASE WHEN ViewHrInfo='1' THEN '√' ELSE '' END  AS ViewHrInfo,CASE WHEN ViewHrChange='1' THEN '√' ELSE '' END  AS ViewHrChange,CASE WHEN ViewAttendance='1' THEN '√' ELSE '' END  AS ViewAttendance,"
                + "CASE WHEN ViewWatching='1' THEN '√' ELSE '' END  AS ViewWatching,CASE WHEN EditWatching='1' THEN '√' ELSE '' END  AS EditWatching,CASE WHEN EditKey='1' THEN '√' ELSE '' END  AS EditKey,CASE WHEN UseKey='1' THEN '√' ELSE '' END  AS UseKey,CASE WHEN EditKeyUsing='1' THEN '√' ELSE '' END  AS EditKeyUsing,CASE WHEN EditTrust='1' THEN '√' ELSE '' END  AS EditTrust,CASE WHEN CancelLockHouse='1' THEN '√' ELSE '' END  AS CancelLockHouse,CASE WHEN ViewPrivCustomer='1' THEN '√' ELSE '' END  AS ViewPrivCustomer,CASE WHEN EditPubDemand='1' THEN '√' ELSE '' END  AS EditPubDemand,CASE WHEN EditPrivDemand='1' THEN '√' ELSE '' END  AS EditPrivDemand,CASE WHEN ViewTelLog='1' THEN '√' ELSE '' END  AS ViewTelLog,CASE WHEN ViewBusiness='1' THEN '√' ELSE '' END  AS ViewBusiness,"
                + "CASE WHEN ViewVacation='1' THEN '√' ELSE '' END  AS ViewVacation,CASE WHEN ViewAnnualLeave='1' THEN '√' ELSE '' END  AS ViewAnnualLeave,CASE WHEN ViewUserLog='1' THEN '√' ELSE '' END  AS ViewUserLog,CASE WHEN DelHouse='1' THEN '√' ELSE '' END  AS DelHouse,CASE WHEN EditPubCustomer='1' THEN '√' ELSE '' END  AS EditPubCustomer,CASE WHEN EditPrivCustomer='1' THEN '√' ELSE '' END  AS EditPrivCustomer,CASE WHEN ViewStock='1' THEN '√' ELSE '' END  AS ViewStock,CASE WHEN IsControl='1' THEN '√' ELSE '' END  AS IsControl,"
                + "CASE WHEN ShiftPubCustomer='1' THEN '√' ELSE '' END  AS ShiftPubCustomer,CASE WHEN SetPubLevel='1' THEN '√' ELSE '' END  AS SetPubLevel,CASE WHEN ViewCrossPubShareDemand='1' THEN '√' ELSE '' END  AS ViewCrossPubShareDemand,CASE WHEN ViewPubShareDemand='1' THEN '√' ELSE '' END  AS ViewPubShareDemand,CASE WHEN ViewCrossPubShareCustomer='1' THEN '√' ELSE '' END  AS ViewCrossPubShareCustomer,CASE WHEN ViewPubShareCustomer='1' THEN '√' ELSE '' END  AS ViewPubShareCustomer,CASE WHEN viewtrace='1' THEN '√' ELSE '' END  AS viewtrace,CASE WHEN CanDeletePicture='1' THEN '√' ELSE '' END  AS CanDeletePicture,CASE WHEN CanUploadPicture='1' THEN '√' ELSE '' END  AS CanUploadPicture,CASE WHEN CanPublishHouse='1' THEN '√' ELSE '' END  AS CanPublishHouse";
            string FieldList = "RecordId,UserCode,UserName,IsBelong,IsRoleA,IsRoleB,IsRoleC,IsRoleD,IsRoleE,IsRoleF,ViewPubHouse,ViewPrivHouse,ViewHideHouse,ViewPrivDemand,ViewRealCustomer,ViewFakeCustomer,EditPrimaryHouse,EditNormalHouse,DelTrace,CanProtect,CanLockHouse,ViewLockHouse,ViewChange,CanChangeConfirm,ViewEntrust,CanCancelTrust,UnCancelTrust,CanDelTrust,ViewWatching,EditWatching,EditKey,UseKey,EditKeyUsing,EditTrust,CancelLockHouse,ViewPrivCustomer,EditPubDemand,EditPrivDemand,ViewTelLog,ViewBusiness,ViewHrInfo,ViewHrChange,ViewAttendance,ViewVacation,ViewAnnualLeave,ViewUserLog,DelHouse,EditPubCustomer,EditPrivCustomer,ViewStock,IsControl,ShiftPubCustomer,SetPubLevel,ViewCrossPubShareDemand,ViewPubShareDemand,ViewCrossPubShareCustomer,ViewPubShareCustomer,viewtrace,CanDeletePicture,CanUploadPicture,CanPublishHouse";


            //当前部门ID
            string departid = context.Request.Params["depid"];
            string strwhere = string.Format("DepartId='{0}'", departid);

            DataSet list = Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.GetList(iPageIndex, iPageSize, strOrder, tablename, strwhere, FieldList, TableFieldList,true);

            int count = (int)list.Tables[1].Rows[0][0];
            string strHtml = "";
            if (!GetKeyListHtml(list, out strHtml))
            {
                context.Response.Write(string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误:" + strHtml));
            }
            list.Dispose();
            list = null;
            context.Response.Write(string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',data:'{2}'}}}}", "成功", count, strHtml));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message));
        }
    }

    /// <summary>
    /// 返回列表；
    /// 根据查询参数生成查询条件1,根据权限设定生成查询条件2；
    /// 返回Json数据：{count:'30',data:'abc'}
    /// </summary>
    /// <param name="context"></param>
    private bool GetKeyListHtml(System.Data.DataSet dslist, out string strHtml)
    {
        try
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("<table style=\"width:4500px;height:100%;\" cellspacing=\"1\" class=\"tabsorternew\" id=\"report\">");
            sb.Append("<thead><tr>");
            sb.Append("<th width=\"100\">工号</th>");
            sb.Append("<th width=\"120\">姓名</th>");
            sb.Append("<th width=\"40\" >隶属</th>");
            sb.Append("<th width=\"40\" >管辖</th>");
            sb.Append("<th width=\"45\" >业务员</th>");
            sb.Append("<th width=\"45\" >秘书</th>");
            sb.Append("<th width=\"40\" >店长</th>");
            sb.Append("<th width=\"40\" >高经</th>");
            sb.Append("<th width=\"40\">区经</th>");
            sb.Append("<th width=\"40\">商经</th>");            
            sb.Append("<th width=\"40\" >公盘</th>");
            sb.Append("<th width=\"40\" >私盘</th>");
            sb.Append("<th width=\"75\">查隐藏盘源</th>");
            sb.Append("<th width=\"60\">删除房源</th>");

            //sb.Append("<th width=\"60\">公客信息</th>");
            
            sb.Append("<th width=\"100\">客源公开级别</th>");
            
            sb.Append("<th width=\"60\">私客信息</th>");
            
            sb.Append("<th width=\"150\">查看部门共享客户</th>");
            sb.Append("<th width=\"150\">查看跨部门共享客户</th>");

            sb.Append("<th width=\"100\">转移公开客源</th>");
            
            sb.Append("<th width=\"60\">修改公客</th>");
            sb.Append("<th width=\"60\">修改私客</th>");
            
            //sb.Append("<th width=\"60\">公客需求</th>");
            sb.Append("<th width=\"60\">私客需求</th>");

            sb.Append("<th width=\"150\">查看部门共享客需</th>");
            sb.Append("<th width=\"150\">查看跨部门共享客需</th>");

            sb.Append("<th width=\"60\">修改公需</th>");
            sb.Append("<th width=\"60\">修改私需</th>");
            
            sb.Append("<th width=\"50\">真业主</th>");
            sb.Append("<th width=\"50\">假业主</th>");
            sb.Append("<th width=\"120\">修改房源关键字段</th>");
            sb.Append("<th width=\"130\">修改房源非关键字段</th>");
            sb.Append("<th width=\"60\">查看跟单</th>");
            sb.Append("<th width=\"60\">删除跟单</th>");
            sb.Append("<th width=\"90\">保护/取消保护</th>");
            sb.Append("<th width=\"60\">封盘操作</th>");
            sb.Append("<th width=\"60\">取消封盘</th>");
            
            sb.Append("<th width=\"60\">查看封盘</th>");
            
            sb.Append("<th width=\"60\">查看带看</th>");
            sb.Append("<th width=\"60\">修改带看</th>");
            sb.Append("<th width=\"60\">修改钥匙</th>");
            sb.Append("<th width=\"60\">钥匙使用</th>");
            sb.Append("<th width=\"100\">修改钥匙使用</th>");
            
            
            sb.Append("<th width=\"60\">查看变更</th>");
            sb.Append("<th width=\"60\">处理变更</th>");
            sb.Append("<th width=\"60\">查看委托</th>");
            sb.Append("<th width=\"60\">修改委托</th>");
            
            sb.Append("<th width=\"60\">作废委托</th>");
            sb.Append("<th width=\"60\">取消作废</th>");
            sb.Append("<th width=\"60\">删除委托</th>");
            
            sb.Append("<th width=\"100\">可查人事信息</th>");
            sb.Append("<th width=\"100\">可查人事变动</th>");
            sb.Append("<th width=\"60\">可查考勤</th>");
            sb.Append("<th width=\"60\">可查休假</th>");
            sb.Append("<th width=\"60\">可查年假</th>");
            sb.Append("<th width=\"60\">可查库存</th>");
            sb.Append("<th width=\"100\">可查电话日志</th>");
            sb.Append("<th width=\"100\">可查营业动态</th>");
            sb.Append("<th width=\"120\">可查用户操作日志</th>");

            sb.Append("<th width=\"120\">可上传房源图片</th>");
            sb.Append("<th width=\"120\">可删除房源图片</th>");
            sb.Append("<th width=\"100\">可推送房源</th>");
            
            sb.Append("</tr></thead><tbody>");

            foreach (System.Data.DataRow row in dslist.Tables[0].Rows)
            {
                sb.AppendFormat("<tr id=\"{0}\" class=\"tr_houselist\">", row["RecordId"].ToString());
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "UserCode", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "UserName", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "IsBelong", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "IsControl", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "IsRoleA", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "IsRoleF", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "IsRoleB", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "IsRoleC", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "IsRoleD", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "IsRoleE", ""));                
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ViewPubHouse", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ViewPrivHouse", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ViewHideHouse", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "DelHouse", ""));

                //sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ViewPubCustomer", ""));

                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "SetPubLevel", ""));
                
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ViewPrivCustomer", ""));

                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ViewPubShareCustomer", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ViewCrossPubShareCustomer", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ShiftPubCustomer", ""));
                
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "EditPubCustomer", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "EditPrivCustomer", ""));
                
//                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ViewPubDemand", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ViewPrivDemand", ""));

                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ViewPubShareDemand", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ViewCrossPubShareDemand", ""));

                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "EditPubDemand", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "EditPrivDemand", ""));
                
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ViewRealCustomer", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ViewFakeCustomer", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "EditPrimaryHouse", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "EditNormalHouse", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "viewTrace", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "DelTrace", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "CanProtect", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "CanLockHouse", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "CancelLockHouse", ""));
                
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ViewLockHouse", ""));

                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ViewWatching", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "EditWatching", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "EditKey", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "UseKey", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "EditKeyUsing", ""));
                
                
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ViewChange", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "CanChangeConfirm", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ViewEntrust", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "EditTrust", ""));
                
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "CanCancelTrust", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "UnCancelTrust", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "CanDelTrust", ""));

                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ViewHrInfo", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ViewHrChange", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ViewAttendance", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ViewVacation", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ViewAnnualLeave", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ViewStock", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ViewTelLog", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ViewBusiness", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ViewUserLog", ""));

                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "CanUploadPicture", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "CanDeletePicture", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "CanPublishHouse", ""));
                             
                sb.Append("</tr>");
            }
            sb.Append("</tbody></table>");
            strHtml = sb.ToString();
            return true;
        }
        catch (Exception ex)
        {
            strHtml = ex.Message;
            return false;
        }
    }
    
    //当前部门信息
    public void getDepartInfo(HttpContext context)
    {
        string strDepartId = context.Request.Params["modelid"];

        try
        {
            string strKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, strDepartId);
            Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo entDepartInfo;
            entDepartInfo = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strKey);
            if (!cs.Hit)
            {
                Chenxin.Lib.Hr.BLL.Hr_DepartmentInfo bllDepartInfo = new Chenxin.Lib.Hr.BLL.Hr_DepartmentInfo();
                entDepartInfo = bllDepartInfo.GetModel(new Guid(strDepartId));
                if (entDepartInfo != null) cs.Set(strKey, entDepartInfo);
            }
            context.Response.Write(string.Format("{{success:'1',msg:'成功',data:{{model:{0}}}}}",
                Chenxin.Lib.Utility.JsonHelp.Convert2Json(entDepartInfo)));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message));
        }
    }
    
    //得到树形结构
    public void GetTree(HttpContext context)
    {
        try
        {
            string fatherid = context.Request.Params["fatherid"];
            string type = context.Request.Params["type"];
            //查询权限判断
            System.Text.StringBuilder str = new System.Text.StringBuilder();

            //查看所有节点权限
            if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewAllNode))
            {
                str.Append(" (1=1) ");
            }
            //查看本城市节点权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCityNode))
            {
                str.AppendFormat(" cityid='{0}' ",CurrentUserInfo.CityId);
            }
            //查看本公司节点权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCompanyNode))
            {
                if (type != "0")
                    str.AppendFormat(" companyid='{0}' ", CurrentUserInfo.CompanyId);
                else
                    str.AppendFormat(" cityid='{0}' ", CurrentUserInfo.CityId);
            }
            //没有权限
            else
            {
                str.Append(" (1=0) ");
            }

            str.AppendFormat(" and ParentId='{0}' ", fatherid);
            
            //权限判断结束
            
            Chenxin.Lib.Hr.BLL.OrganizationManage bllOrgManage = new Chenxin.Lib.Hr.BLL.OrganizationManage();
            List<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo> dep = bllOrgManage.GetListBySql(str.ToString());
            StringBuilder sb = new StringBuilder();
            if (dep.Count > 0)
            {
                foreach (Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo d in dep)
                {
                    sb.AppendFormat("{{DepartId:'{0}',DepartCode:'{1}',DepartName:'{2}',DepartProperty:'{3}',CityId:'{4}',City:'{5}',CompanyId:'{6}',CompanyName:'{7}'}},", d.DepartId.ToString(),d.DepartCode,d.DepartName,d.DepartProperty,d.CityId.ToString(),d.City,d.CompanyId.ToString(),d.CompanyName);
                }
                sb.Remove(sb.Length - 1, 1);
            }
            context.Response.Write(string.Format("{{sucess:1,msg:'',data:{{items:[{0}]}}}}",sb.ToString()));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message));
        }
    }

    //添加节点
    private void AddDep(HttpContext context)
    {
        Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo dep = (Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo)JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo));
        string ParentId = context.Request.Params["fatherid"];
        dep.DepartId = Guid.NewGuid();
        
        Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo parentdep = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(new Guid(ParentId));
        switch (dep.DepartProperty)
        {
            //城市
            case 100:
                dep.CityId = dep.DepartId;
                dep.City = dep.DepartName;
                dep.DepartSrc = dep.DepartCode + "/";
                dep.IsOpen = true;
                break;
            //公司
            case 200:
                dep.City = parentdep.City;
                dep.CityId = parentdep.CityId;
                dep.CompanyId = dep.DepartId;
                dep.CompanyName = dep.DepartName;
                dep.DepartSrc = parentdep.DepartSrc + dep.DepartCode + "/";
                dep.IsOpen = true;
                string UseBlockRole = context.Request.Params["AreaUse"];
                string BlockRoleNum = context.Request.Params["AreaType"];
                Chenxin.Lib.House.Entity.House_BusinessSetting hbs = new Chenxin.Lib.House.Entity.House_BusinessSetting();
                hbs.UseBlockRole = bool.Parse(UseBlockRole);
                hbs.BlockRoleNum = int.Parse(BlockRoleNum);
                hbs.DepartId = dep.DepartId;
                Chenxin.Lib.House.DAL.House_BusinessSetting.Add(hbs);
                break;
            //商圈
            case 300:
                dep.City = parentdep.City;
                dep.CityId = parentdep.CityId;
                dep.CompanyId = parentdep.CompanyId;
                dep.CompanyName = parentdep.CompanyName;
                dep.DepartSrc = parentdep.DepartSrc + dep.DepartCode + "/";
                //dep.IsOpen = true;
                break;
            //分类
            case 400:
                dep.City = parentdep.City;
                dep.CityId = parentdep.CityId;
                dep.CompanyId = parentdep.CompanyId;
                dep.CompanyName = parentdep.CompanyName;
                dep.DepartSrc = parentdep.DepartSrc + dep.DepartCode + "/";
                //dep.IsOpen = true;
                break;
            //部门
            case 500:
                dep.City = parentdep.City;
                dep.CityId = parentdep.CityId;
                dep.CompanyId = parentdep.CompanyId;
                dep.CompanyName = parentdep.CompanyName;
                dep.DepartSrc = parentdep.DepartSrc + dep.DepartCode;
                
                //添加部门参数
                Chenxin.Lib.House.Entity.House_BusinessSetting dep_setting = (Chenxin.Lib.House.Entity.House_BusinessSetting)JsonHelp.Convert2Entity(context.Request["settingModel"], typeof(Chenxin.Lib.House.Entity.House_BusinessSetting));
                dep_setting.DepartId = dep.DepartId;
                Chenxin.Lib.House.DAL.House_BusinessSetting.Add(dep_setting);
                
                //添加部门参数默认值
                string strSql = string.Format("insert into HR_Rel_Purview(RecodID,DepartID,TermsName,ViewPubHouse,ViewPrivHouse,ViewHideHouse,ViewPrivDemand,ViewRealCustomer,ViewFakeCustomer,EditPrimaryHouse,EditNormalHouse,DelTrace,CanProtect,CanLockHouse,ViewLockHouse,ViewChange,CanChangeConfirm,ViewEntrust,CanCancelTrust,UnCancelTrust,CanDelTrust,ViewWatching,EditWatching,EditKey,UseKey,EditKeyUsing,EditTrust,CancelLockHouse,ViewPrivCustomer,EditPubDemand,EditPrivDemand,ViewTelLog,ViewBusiness,ViewHrInfo,ViewHrChange,ViewAttendance,ViewVacation,ViewAnnualLeave,ViewUserLog,DelHouse,EditPubCustomer,EditPrivCustomer,ViewStock,IsControl,Addtime,ShiftPubCustomer,SetPubLevel,ViewCrossPubShareDemand,ViewPubShareDemand,ViewCrossPubShareCustomer,ViewPubShareCustomer,viewtrace,CanDeletePicture,CanUploadPicture,CanPublishHouse) select newid(),'{0}',TermsName,ViewPubHouse,ViewPrivHouse,ViewHideHouse,ViewPrivDemand,ViewRealCustomer,ViewFakeCustomer,EditPrimaryHouse,EditNormalHouse,DelTrace,CanProtect,CanLockHouse,ViewLockHouse,ViewChange,CanChangeConfirm,ViewEntrust,CanCancelTrust,UnCancelTrust,CanDelTrust,ViewWatching,EditWatching,EditKey,UseKey,EditKeyUsing,EditTrust,CancelLockHouse,ViewPrivCustomer,EditPubDemand,EditPrivDemand,ViewTelLog,ViewBusiness,ViewHrInfo,ViewHrChange,ViewAttendance,ViewVacation,ViewAnnualLeave,ViewUserLog,DelHouse,EditPubCustomer,EditPrivCustomer,ViewStock,IsControl,getdate(),ShiftPubCustomer,SetPubLevel,ViewCrossPubShareDemand,ViewPubShareDemand,ViewCrossPubShareCustomer,ViewPubShareCustomer,viewtrace,CanDeletePicture,CanUploadPicture,CanPublishHouse from HR_Rel_Purview where DepartID='{1}';", dep.DepartId.ToString(), dep.CompanyId.ToString());
                Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.ExecuteSQL(strSql);
                break;

            //其他部门
            case 600:
                goto case 500;

        }
        dep.AddPerson = CurrentUserInfo.UserName;
        dep.AddTime = DateTime.Now;
        Chenxin.Lib.Hr.BLL.OrganizationManage bllOrgManage = new Chenxin.Lib.Hr.BLL.OrganizationManage();
        try
        {
            bllOrgManage.AddSubTree(new Guid(ParentId), dep);

            string strCacheKey = "";
            if (dep.DepartProperty == 100)
            {
                Chenxin.Lib.Hr.Entity.Struct_CityBaseInfo cityinfo = new Chenxin.Lib.Hr.Entity.Struct_CityBaseInfo();
                cityinfo.CityId = dep.DepartId;
                cityinfo.CityCode = dep.DepartCode.ToUpper();
                cityinfo.CityName = dep.DepartName;
                Chenxin.Lib.Hr.DAL.Struct_CityBaseInfo.Add(cityinfo);

                //删除城市缓存                
                strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_CITYS);
                cs.Delete(strCacheKey);
            }

            //添加日志
            //AddUserLogs(dep, "add");
            AddLog("" + CurrentUserInfo.UserName + "添加节点:节点名称[" + dep.DepartName+ "]",
                    OperationType.OperationTypeComboList()["OprType_AddNode"].ToString()); 

            context.Response.Write(string.Format("{{sucess:1,msg:'添加成功',data:''}}"));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message));
        }
    }

    

    //编辑节点
    public void EditDep(HttpContext context)
    {
        try
        {
            Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo dep = (Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo)JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo));

            string strCacheKey = "";
            string strSql="";
            //修改商圈或分类
            if (dep.DepartProperty != 500 && dep.DepartProperty != 600)
            {
                if (dep.DepartProperty == 100)
                {
                    string sql = string.Format("update Struct_CityBaseInfo set CityName='{0}' where CityId='{1}';", dep.DepartName, dep.DepartId);
                    Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.ExecuteSQL(sql);
                    
                    strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_CITYS);
                    cs.Delete(strCacheKey);
                    strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_STRUCT_FULL);
                    cs.Delete(strCacheKey);                    
                }
                strSql = string.Format("update Hr_DepartmentInfo set DepartName='{0}',IsOpen='{2}',IsCalculate='{3}' where DepartId='{1}';", dep.DepartName, dep.DepartId, dep.IsOpen,dep.IsCalculate);
                if (dep.DepartProperty == 200)
                {
                    Chenxin.Lib.House.DAL.House_BusinessSetting.Delete(dep.DepartId);
                    string UseBlockRole = context.Request.Params["AreaUse"];
                    string BlockRoleNum = context.Request.Params["AreaType"];
                    Chenxin.Lib.House.Entity.House_BusinessSetting hbs = new Chenxin.Lib.House.Entity.House_BusinessSetting();
                    hbs.UseBlockRole = bool.Parse(UseBlockRole);
                    hbs.BlockRoleNum = int.Parse(BlockRoleNum);
                    hbs.DepartId = dep.DepartId;
                    Chenxin.Lib.House.DAL.House_BusinessSetting.Add(hbs);
                }
                Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.ExecuteSQL(strSql);
            }
            //修改部门信息
            else
            {
                //修改部门参数
                Chenxin.Lib.House.Entity.House_BusinessSetting dep_setting = (Chenxin.Lib.House.Entity.House_BusinessSetting)JsonHelp.Convert2Entity(context.Request["settingModel"], typeof(Chenxin.Lib.House.Entity.House_BusinessSetting));
                dep_setting.DepartId = dep.DepartId;

                //更新部门参数
                Chenxin.Lib.House.DAL.House_BusinessSetting.Update(dep_setting);
                    
                //更新部门基本信息
                Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.Update(dep);                               
            }            
            //添加操作日志
            //AddUserLogs(dep, "update");

            AddLog("" + CurrentUserInfo.UserName + "编辑节点:节点名称[" + dep.DepartName + "]",
                    OperationType.OperationTypeComboList()["OprType_EditNode"].ToString());

            strSql = string.Format("ChildId='{0}'", dep.DepartId);
            List<Chenxin.Lib.Hr.Entity.Hr_Struct_DepartTreeRelation> list = Chenxin.Lib.Hr.DAL.Hr_Struct_DepartTreeRelation.GetListArray(strSql);
            if (list.Count > 0)
            {
                Guid parentId = list[0].ParentId;
                //删除组织结构 商圈部门 缓存
                strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_STRUCT_TREE, parentId);
                cs.Delete(strCacheKey);

                Chenxin.Lib.Cache.CacheService cs2 = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                string strCachKey2 = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, parentId);
                cs2.Delete(strCachKey2);
            } 

            //删除公司下商圈分类的缓存
            strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_STRUCT_TREE, dep.CompanyId + ".4000");
            cs.Delete(strCacheKey);
            strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_STRUCT_TREE, dep.CompanyId + ".5000");
            cs.Delete(strCacheKey);
            
            //删除部门信息缓存
            strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, dep.DepartId);
            cs.Delete(strCacheKey);

            //删除部门设定缓存
            strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPART_SETTINGS, dep.DepartId);
            cs.Delete(strCacheKey);

            context.Response.Write(string.Format("{{sucess:1,msg:'更新成功',data:''}}"));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message));
        }
    }
    
    //删除节点
    public void DelDep(HttpContext context)
    {
        string strDepartId = context.Request.Params["modelid"];
        string strKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, strDepartId);
        Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo dep;
        //根据ID得到部门数据
        dep = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strKey);
        if (!cs.Hit)
        {
            Chenxin.Lib.Hr.BLL.Hr_DepartmentInfo bllDepartInfo = new Chenxin.Lib.Hr.BLL.Hr_DepartmentInfo();
            dep = bllDepartInfo.GetModel(new Guid(strDepartId));
            if (dep != null) cs.Set(strKey, dep);
        }

        Chenxin.Lib.Hr.BLL.OrganizationManage bllOrgManage = new Chenxin.Lib.Hr.BLL.OrganizationManage();
        try
        {
            if (!hasChildDepart(dep))
            {
                if (dep.DepartProperty == 100)
                {
                    string strSql = string.Format("delete Struct_CityBaseInfo where CityId='{0}'", dep.DepartId.ToString());
                    Chenxin.Lib.Passport.DAL.Hr_UserInfo.ExecuteSQL(strSql);

                    //删除城市缓存                
                    string strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_CITYS);
                    cs.Delete(strCacheKey);
                }
                //删除节点关系及节点信息、缓存
                bllOrgManage.DeleteLeaf(dep.DepartId);
                //删除部门设定
                Chenxin.Lib.House.DAL.House_BusinessSetting.Delete(dep.DepartId);

                //删除部门设定缓存
                if (dep.DepartProperty == 500 || dep.DepartProperty == 600||dep.DepartProperty==200)
                {
                    string strCacheKey_setting = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPART_SETTINGS, dep.DepartId.ToString());
                    cs.Delete(strCacheKey_setting);
                }

                //添加操作日志
                //AddUserLogs(dep, "del");

                AddLog("" + CurrentUserInfo.UserName + "删除节点:节点名称[" + dep.DepartName + "]",
                   OperationType.OperationTypeComboList()["OprType_DelNode"].ToString());

                context.Response.Write(string.Format("{{sucess:1,msg:'删除成功',data:''}}"));
            }
            else
                context.Response.Write(string.Format("{{sucess:0,msg:'该部门有子节点或隶属的人员，无法删除！',data:''}}"));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message));
        }
    }

    //查询是否有子节点及隶属的人员
    public bool hasChildDepart(Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo dep)
    {
        try
        {
            string strDepartId = dep.DepartId.ToString();
            string strSql = string.Format("select acount+bcount from (select count(*) as acount from Struct_UserDepartRelation where DepartId='{0}' and IsBelong='true')a,(select count(*) as bcount from Hr_Struct_DepartTreeRelation where ParentId='{1}')b", strDepartId, strDepartId);
            bool flag = Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.SearchSQL(strSql);
            return flag;
        }
        catch (Exception ex)
        {
            return true;
        }
    }
    
    //转移节点
    private void MoveDep(HttpContext context)
    {
        string id = "";     //部门ID
        string parentid = "";   //父节点ID
        string depname = "";    //部门名称
        if (!string.IsNullOrEmpty(context.Request.Params["depid"]))
        {
            id = context.Request.Params["depid"];
        }
        if (!string.IsNullOrEmpty(context.Request.Params["parentid"]))
        {
            parentid = context.Request.Params["parentid"];
        }
        if (!string.IsNullOrEmpty(context.Request.Params["depname"]))
        {
            depname = context.Request.Params["depname"];
        }
        List<Chenxin.Lib.Hr.Entity.Hr_Struct_DepartTreeRelation> utr = Chenxin.Lib.Hr.DAL.Hr_Struct_DepartTreeRelation.GetListArray("ChildId='"+id+"'");
        if (utr.Count > 0)
        {
            //删除组织结构缓存
            string strCacheKey_old = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_STRUCT_TREE, utr[0].ParentId);
            cs.Delete(strCacheKey_old);
        }
        
        string strSql = "";
        strSql += string.Format("delete Hr_Struct_DepartTreeRelation where ChildId='{0}';", id);
        strSql += string.Format("update Hr_DepartmentInfo set DepartSrc=(select DepartSrc from Hr_DepartmentInfo where DepartId='{0}')+DepartCode where DepartId='{1}';", parentid, id);
        strSql += string.Format("insert into Hr_Struct_DepartTreeRelation VALUES(newid(),'{0}','{1}');", parentid, id);
        //添加日志
        //strSql += string.Format("insert into Hr_UserLogs values(newid(),'{0}','{1}','{2}','{3}','{4}','转移节点','{2}-转移节点:{5}',getdate());", id, CurrentUserInfo.UserId.ToString(), CurrentUserInfo.UserName, CurrentUserInfo.DepartId.ToString(), CurrentUserInfo.DepartName, depname);
        try
        {
            Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.ExecuteSQL(strSql);

            //删除组织结构缓存
            string strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_STRUCT_TREE, parentid);
            cs.Delete(strCacheKey);

            AddLog("" + CurrentUserInfo.UserName + "转移节点:节点名称[" + depname + "]",
                   OperationType.OperationTypeComboList()["OprType_MoveNode"].ToString());

            context.Response.Write(string.Format("{{sucess:1,msg:'转移成功',data:''}}"));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message));
        }
    }
    
    //密码重置
    public void resetPassword(HttpContext context)
    {
        string strUserId = context.Request.Params["userid"];
        string strNewPwd = context.Request.Params["newpwd"];

        Chenxin.Lib.Passport.BLL.Hr_UserInfo bllUserInfo = new Chenxin.Lib.Passport.BLL.Hr_UserInfo();

        try
        {
            Chenxin.Lib.Passport.Entity.Hr_UserInfo hrinfo = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetEntityById(strUserId);
            
            bllUserInfo.ResetPassword(new Guid(strUserId), strNewPwd);

            AddLog("" + CurrentUserInfo.UserName + "密码重置:员工姓名[" + hrinfo.UserName + "("+hrinfo.UserCode+")]",
                   OperationType.OperationTypeComboList()["OprType_ResetPwd"].ToString());
            
            context.Response.Write(string.Format("{{sucess:1,msg:'密码重置成功',data:''}}"));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message));
        }
    }

    //设置业务所属地
    private void setLocal(HttpContext context)
    {
        try
        {
            //员工ID
            string userid = context.Request.Params["userid"];
            //工号
            string usercode = context.Request.Params["usercode"];
            //城市ID
            string cityid = context.Request.Params["cityid"];
            //城市
            string city = context.Request.Params["city"];
            //公司ID
            string companyid = context.Request.Params["companyid"];
            //公司
            string company = context.Request.Params["company"];
            //部门ID
            string depid = context.Request.Params["depid"];
            //部门
            string dep = context.Request.Params["dep"];

            Chenxin.Lib.Passport.Entity.Hr_UserInfo userinfo = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetEntityById(new Guid(userid));

            //删除缓存
            string strGKeyUser = string.Format(Chenxin.Lib.Cache.CacheDataType.USER, userid);
            cs.Delete(strGKeyUser);
            strGKeyUser = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_USER, userid);
            cs.Delete(strGKeyUser);
            strGKeyUser = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, userinfo.DepartId);
            cs.Delete(strGKeyUser);
            strGKeyUser = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT,depid);
            cs.Delete(strGKeyUser);
            strGKeyUser = string.Format(Chenxin.Lib.Cache.CacheDataType.HR_DEPARTUSERS, userinfo.DepartId);
            cs.Delete(strGKeyUser);
            strGKeyUser = string.Format(Chenxin.Lib.Cache.CacheDataType.HR_DEPARTUSERS, depid);
            cs.Delete(strGKeyUser);
            strGKeyUser = string.Format(Chenxin.Lib.Cache.CacheDataType.HR_DEPARTMENT_USERS, userinfo.DepartId+".0");
            cs.Delete(strGKeyUser);
            strGKeyUser = string.Format(Chenxin.Lib.Cache.CacheDataType.HR_DEPARTMENT_USERS, depid+".0");
            cs.Delete(strGKeyUser);
            strGKeyUser = string.Format(Chenxin.Lib.Cache.CacheDataType.HR_DEPARTMENT_USERS, userinfo.DepartId + ".1");
            cs.Delete(strGKeyUser);
            strGKeyUser = string.Format(Chenxin.Lib.Cache.CacheDataType.HR_DEPARTMENT_USERS, depid + ".1");
            cs.Delete(strGKeyUser);
            strGKeyUser = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_KEYUSEINFO, userid);
            cs.Delete(strGKeyUser);            
            
            string strSql = string.Format("update Hr_UserInfo set CityId='{0}',CityName='{1}',CompanyId='{2}',CompanyName='{3}',DepartId='{4}',DepartName='{5}' where UserCode='{6}';", cityid, city, companyid, company, depid, dep, usercode);

            if (userinfo.BelongDepartId.ToString() != depid)
            {
                strSql += string.Format("delete Struct_UserDepartRelation where DepartId='{0}' and UserId='{1}';",depid,userid);
                strSql += string.Format("insert into Struct_UserDepartRelation(RecordId,DepartId,DepartName,UserId,UserCode,UserName,IsBelong,ViewPubHouse,ViewPrivHouse,ViewHideHouse,ViewPrivDemand,ViewRealCustomer,ViewFakeCustomer,EditPrimaryHouse,EditNormalHouse,DelTrace,CanProtect,CanLockHouse,ViewLockHouse,ViewChange,CanChangeConfirm,ViewEntrust,CanCancelTrust,UnCancelTrust,CanDelTrust,ViewWatching,EditWatching,EditKey,UseKey,EditKeyUsing,EditTrust,CancelLockHouse,ViewPrivCustomer,EditPubDemand,EditPrivDemand,ViewTelLog,ViewBusiness,ViewHrInfo,ViewHrChange,ViewAttendance,ViewVacation,ViewAnnualLeave,ViewUserLog,DelHouse,EditPubCustomer,EditPrivCustomer,ViewStock,IsControl,Addtime,ShiftPubCustomer,SetPubLevel,ViewCrossPubShareDemand,ViewPubShareDemand,ViewCrossPubShareCustomer,ViewPubShareCustomer,viewtrace,CanDeletePicture,CanUploadPicture,CanPublishHouse) ");
                strSql += string.Format("select newid(),'{0}','{1}',UserId,UserCode,UserName,0,ViewPubHouse,ViewPrivHouse,ViewHideHouse,ViewPrivDemand,ViewRealCustomer,ViewFakeCustomer,EditPrimaryHouse,EditNormalHouse,DelTrace,CanProtect,CanLockHouse,ViewLockHouse,ViewChange,CanChangeConfirm,ViewEntrust,CanCancelTrust,UnCancelTrust,CanDelTrust,ViewWatching,EditWatching,EditKey,UseKey,EditKeyUsing,EditTrust,CancelLockHouse,ViewPrivCustomer,EditPubDemand,EditPrivDemand,ViewTelLog,ViewBusiness,ViewHrInfo,ViewHrChange,ViewAttendance,ViewVacation,ViewAnnualLeave,ViewUserLog,DelHouse,EditPubCustomer,EditPrivCustomer,ViewStock,1,getdate(),ShiftPubCustomer,SetPubLevel,ViewCrossPubShareDemand,ViewPubShareDemand,ViewCrossPubShareCustomer,ViewPubShareCustomer,viewtrace,CanDeletePicture,CanUploadPicture,CanPublishHouse from Struct_UserDepartRelation where userid='{2}' and IsBelong=1;", depid, dep, userid);
            }
            
            bool flag = Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.ExecuteSQL(strSql);

            if (flag)
            {
                AddLog("" + CurrentUserInfo.UserName + "设置业务所属地:员工姓名[" + userinfo.UserName + "(" + userinfo.UserCode + ")]",
                   OperationType.OperationTypeComboList()["OprType_BusinessLocal"].ToString());
                
                context.Response.Write(string.Format("{{sucess:1,msg:'设置成功',data:''}}"));                
            }
            else
                context.Response.Write(string.Format("{{success:1,msg:'工号:{0}不存在！',data:''}}", usercode));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message));
        }
    }

    //根据用户工号得到用户信息
    private void getUserByCode(HttpContext context)
    {
        try
        {
            string usercode = context.Request.QueryString["usercode"];
            Chenxin.Lib.Passport.Entity.Hr_UserInfo userinfo = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetEntityByCode(usercode);
            if (userinfo != null){
                if(userinfo.Status==1)
                    context.Response.Write(string.Format("{{sucess:1,msg:'',data:{{exist:true,userinfo:'{0}',UserId:'{1}'}}}}", userinfo.UserName + "(" + userinfo.BelongDepart + ")", userinfo.UserId.ToString()));
                else
                    context.Response.Write(string.Format("{{success:'1',msg:'',data:{{exist:false}}}}"));
            }
            else
                context.Response.Write(string.Format("{{success:'1',msg:'',data:{{exist:false}}}}"));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message));
        }
    }

    //添加人员
    private void addUser(HttpContext context)
    {
        try
        {
            string stype = "";
            string todepid = "";    //目标门店ID
            string todepname = "";  //目标门店名称
            string depid = "";  //源对象
            string strSql = "";
            string qx = "";     //选中的权限 （列名）
            string tocompany = "";
            string tocompanyid = "";
            string tocity = "";
            string tocityid = "";
            string sub = "";    //添加的方式（重置、追加、剔除）
            string updatestr = "";  //更新的STR

            if (!string.IsNullOrEmpty(context.Request.Params["settingtype"]))
            {
                stype = context.Request.Params["settingtype"];
            }
            if (!string.IsNullOrEmpty(context.Request.Params["depid"]))
            {
                depid = context.Request.Params["depid"];
            }
            if (!string.IsNullOrEmpty(context.Request.Params["aimdepid"]))
            {
                todepid = context.Request.Params["aimdepid"];
            }
            if (!string.IsNullOrEmpty(context.Request.Params["aimdepname"]))
            {
                todepname = context.Request.Params["aimdepname"];
            }
            if (!string.IsNullOrEmpty(context.Request.Params["aimcityid"]))
            {
                tocityid = context.Request.Params["aimcityid"];
            }
            if (!string.IsNullOrEmpty(context.Request.Params["aimcity"]))
            {
                tocity = context.Request.Params["aimcity"];
            }
            if (!string.IsNullOrEmpty(context.Request.Params["aimcompanyid"]))
            {
                tocompanyid = context.Request.Params["aimcompanyid"];
            }
            if (!string.IsNullOrEmpty(context.Request.Params["aimcompany"]))
            {
                tocompany = context.Request.Params["aimcompany"];
            }
            if (!string.IsNullOrEmpty(context.Request.Params["sub"]))
            {
                sub = context.Request.Params["sub"];
            }
            
            
            if (!string.IsNullOrEmpty(context.Request.Params["authority"]))
            {
                qx = context.Request.Params["authority"]+",";
            }
            if (!string.IsNullOrEmpty(context.Request.Params["purview"]))
            {
                qx += context.Request.Params["purview"];
                updatestr = context.Request.Params["purview"];
            }

            string str_qx = "";
            string[] array = qx.Split(',');
            for (int i = 0; i < array.Length; i++)
            {
                str_qx += "'1',";
            }

            string str_up_t = "";       //追加
            string str_up_f = "";       //剔除
            string[] array_up = qx.Split(',');
            for (int i = 0; i < array_up.Length; i++)
            {
                str_up_t += array_up[i] + "=1,";
                str_up_f += array_up[i] + "=0,";
            }

            string role = "";   //选中的角色    （角色id）
            if (!string.IsNullOrEmpty(context.Request.Params["role"]))
            {
                role = context.Request.Params["role"];
            }
            string[] todepid_array = todepid.Split(',');
            string[] todepname_array = todepname.Split(',');
            todepid = todepid.Replace(",", "','");
            todepname = todepname.Replace(",", "','");

            //手动—部门
            if (stype=="10")
            {
                //重置
                if (sub == "10")
                {
                    strSql += string.Format("DELETE Struct_UserDepartRelation WHERE exists (select userid from hr_userinfo where BelongDepartId='{0}' and userid=Struct_UserDepartRelation.userid) and DepartId in ('{1}');", depid, todepid);
                    for (int i = 0; i < todepid_array.Length; i++)
                    {
                        if (depid != todepid_array[i])
                            strSql += string.Format("insert into Struct_UserDepartRelation(RecordId,CityId,City,CompanyId,Company,DepartId,DepartName,UserId,UserCode,UserName,IsBelong,{0},Addtime) select newid(),'{6}','{7}','{8}','{9}','{1}','{2}',UserId,UserCode,UserName,'0',{3},getdate() from Hr_UserInfo where not exists (select UserId from Struct_UserDepartRelation where DepartId='{4}' and userid=Hr_UserInfo.userid) and BelongDepartId='{5}' and [Status]='1' and Validate=1;", qx, todepid_array[i], todepname_array[i], str_qx.Substring(0, str_qx.Length - 1), todepid_array[i], depid, tocityid, tocity, tocompanyid, tocompany);
                        else
                            strSql += string.Format("insert into Struct_UserDepartRelation(RecordId,CityId,City,CompanyId,Company,DepartId,DepartName,UserId,UserCode,UserName,IsBelong,{0},Addtime) select newid(),'{5}','{6}','{7}','{8}','{1}','{2}',UserId,UserCode,UserName,'1',{3},getdate() from Hr_UserInfo where BelongDepartId='{4}' and [Status]='1' and Validate=1;", qx, todepid_array[i], todepname_array[i], str_qx.Substring(0, str_qx.Length - 1), depid, tocityid, tocity, tocompanyid, tocompany);
                    }
                }
                    //追加
                else if (sub == "20")
                {                    
                    for (int i = 0; i < todepid_array.Length; i++)
                    {
                        //存在更新
                        strSql += string.Format("update Struct_UserDepartRelation set {0} where userid in (select userid from hr_userinfo where BelongDepartId='{1}' and [Status]=1 and Validate=1) and departid='{2}';", str_up_t.Substring(0, str_up_t.Length - 1), depid, todepid_array[i]);
                        //不存在插入
                        if (depid != todepid_array[i])
                            strSql += string.Format("insert into Struct_UserDepartRelation(RecordId,CityId,City,CompanyId,Company,DepartId,DepartName,UserId,UserCode,UserName,IsBelong,{0},Addtime) select newid(),'{1}','{2}','{7}','{8}','{3}','{4}',UserId,UserCode,UserName,'0',{5},getdate() from hr_userinfo where userid not in (select userid from Struct_UserDepartRelation where departid='{3}') and [Status]=1 and BelongDepartId='{6}' and Validate=1;", qx, tocityid, tocity, todepid_array[i], todepname_array[i], str_qx.Substring(0, str_qx.Length - 1), depid, tocompanyid, tocompany);
                        else
                            strSql += string.Format("insert into Struct_UserDepartRelation(RecordId,CityId,City,CompanyId,Company,DepartId,DepartName,UserId,UserCode,UserName,IsBelong,{0},Addtime) select newid(),'{1}','{2}','{7}','{8}','{3}','{4}',UserId,UserCode,UserName,'1',{5},getdate() from hr_userinfo where userid not in (select userid from Struct_UserDepartRelation where departid='{3}') and [Status]=1 and BelongDepartId='{6}' and Validate=1;", qx, tocityid, tocity, todepid_array[i], todepname_array[i], str_qx.Substring(0, str_qx.Length - 1), depid, tocompanyid, tocompany);
                    }
                }
                    //剔除
                else if (sub == "30")
                {
                    strSql += string.Format("update Struct_UserDepartRelation set {0} where userid in (select userid from hr_userinfo where BelongDepartId='{1}' and [Status]=1 and Validate=1) and departid in ('{2}');", str_up_f.Substring(0, str_up_f.Length - 1), depid, todepid);
                }
                
            }
            //手动—员工
            else if(stype=="20")
            {
                string usercode = context.Request.Params["usercode"];
                //重置
                if (sub == "10")
                {
                    strSql += string.Format("delete Struct_UserDepartRelation where UserCode='{0}' and DepartId in ('{1}');", usercode, todepid);
                    for (int i = 0; i < todepid_array.Length; i++)
                    {
                        strSql += string.Format("insert into Struct_UserDepartRelation(RecordId,CityId,City,CompanyId,Company,DepartId,DepartName,UserId,UserCode,UserName,IsBelong,{0},Addtime) select newid(),'{1}','{2}','{3}','{4}','{5}','{6}',UserId,UserCode,UserName,case (select 1 from hr_userinfo where BelongDepartId='{5}' and usercode='{7}' ) when 1 then 1 else 0 end,{8},getdate() from Hr_UserInfo where UserCode='{7}';", qx, tocityid, tocity, tocompanyid, tocompany, todepid_array[i], todepname_array[i], usercode, str_qx.Substring(0, str_qx.Length - 1));
                    }
                }
                    //追加
                else if (sub == "20")
                {
                    strSql += string.Format("update Struct_UserDepartRelation set {0},UserName=(select UserName from hr_userinfo where usercode='{1}') where usercode='{1}' and departid in ('{2}');", str_up_t.Substring(0, str_up_t.Length - 1), usercode, todepid);
                    for (int i = 0; i < todepid_array.Length; i++)
                    {
                        strSql += string.Format("insert into Struct_UserDepartRelation(RecordId,CityId,City,CompanyId,Company,DepartId,DepartName,UserId,UserCode,UserName,IsBelong,{0},Addtime) select newid(),'{1}','{2}','{3}','{4}','{5}','{6}',UserId,UserCode,UserName,case (select 1 from hr_userinfo where BelongDepartId='{5}' and usercode='{7}' ) when 1 then 1 else 0 end,{8},getdate() from Hr_UserInfo where UserCode='{7}' and (select count(*) from Struct_UserDepartRelation where usercode='{7}' and departid='{5}')<1;", qx, tocityid, tocity, tocompanyid, tocompany, todepid_array[i], todepname_array[i], usercode, str_qx.Substring(0, str_qx.Length - 1));
                    }
                }
                    //剔除
                else if (sub == "30")
                {
                    strSql += string.Format("update Struct_UserDepartRelation set {0} where usercode='{1}' and departid in ('{2}');", str_up_f.Substring(0, str_up_f.Length - 1), usercode, todepid);
                }
                //如有角色，则进行角色的修改

                if (role.Length > 0)
                {
                    strSql += string.Format("delete Base_RoleUserRelationInfo where UserId=(select UserId from Hr_UserInfo where UserCode='{0}');", usercode);
                    string[] role_array = role.Split(',');
                    for (int i = 0; i < role_array.Length; i++)
                    {
                        strSql += string.Format("insert into Base_RoleUserRelationInfo select newid(),'{0}',UserId from Hr_UserInfo where UserCode='{1}';", role_array[i], usercode);
                    }
                }
            }
            //参照设定
            else if (stype == "30")
            {
                //源对象
                string userid = context.Request.Params["userid"];
                Chenxin.Lib.Passport.Entity.Hr_UserInfo hrinfo = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetEntityById(new Guid(userid));
                //目标对象
                string aimuserid = context.Request.Params["aimuserid"];

                strSql += string.Format("delete Struct_UserDepartRelation where userid='{0}' and IsBelong=0;", userid);
                strSql += string.Format("insert into Struct_UserDepartRelation([RecordId],[CityId],[City],[CompanyId],[Company],[DepartId],[DepartName],[UserId],[UserCode],[UserName],[IsBelong],[IsControl],[IsRoleA],[IsRoleB]"
                       + ",[IsRoleC],[IsRoleD],[IsRoleE],[IsRoleF],[IsRoleG],[IsRoleH],[ViewPubHouse],[ViewPrivHouse],[ViewHideHouse],[ViewPrivDemand]"
                       + ",[ViewRealCustomer],[ViewFakeCustomer],[EditPrimaryHouse],[EditNormalHouse],[DelTrace],[CanProtect],[CanLockHouse],[ViewLockHouse],[ViewChange]"
                       + ",[CanChangeConfirm],[ViewEntrust],[CanCancelTrust],[UnCancelTrust],[CanDelTrust],[ViewWatching],[EditWatching],[EditKey],[UseKey],[EditKeyUsing]"
                       + ",[EditTrust],[CancelLockHouse],[ViewPrivCustomer],[EditPubDemand],[EditPrivDemand],[ViewTelLog],[ViewBusiness],[ViewHrInfo]"
                       + ",[ViewHrChange],[ViewAttendance],[ViewVacation],[ViewAnnualLeave],[ViewUserLog],[DelHouse],[EditPubCustomer],[EditPrivCustomer],[ViewStock]"
                       + ",[ShiftPubCustomer],[SetPubLevel],[ViewCrossPubShareDemand],[ViewPubShareDemand],[ViewCrossPubShareCustomer],[ViewPubShareCustomer],[viewtrace],CanDeletePicture,CanUploadPicture,CanPublishHouse,[Addtime])"
                        + " select newid(),[CityId],[City],[CompanyId],[Company],[DepartId],[DepartName],'{0}','{1}','{2}',0,[IsControl],[IsRoleA],[IsRoleB]"
                        + ",[IsRoleC],[IsRoleD],[IsRoleE],[IsRoleF],[IsRoleG],[IsRoleH],[ViewPubHouse],[ViewPrivHouse],[ViewHideHouse],[ViewPrivDemand]"
                       + ",[ViewRealCustomer],[ViewFakeCustomer],[EditPrimaryHouse],[EditNormalHouse],[DelTrace],[CanProtect],[CanLockHouse],[ViewLockHouse],[ViewChange]"
                       + ",[CanChangeConfirm],[ViewEntrust],[CanCancelTrust],[UnCancelTrust],[CanDelTrust],[ViewWatching],[EditWatching],[EditKey],[UseKey],[EditKeyUsing]"
                       + ",[EditTrust],[CancelLockHouse],[ViewPrivCustomer],[EditPubDemand],[EditPrivDemand],[ViewTelLog],[ViewBusiness],[ViewHrInfo]"
                       + ",[ViewHrChange],[ViewAttendance],[ViewVacation],[ViewAnnualLeave],[ViewUserLog],[DelHouse],[EditPubCustomer],[EditPrivCustomer],[ViewStock]"
                       + ",[ShiftPubCustomer],[SetPubLevel],[ViewCrossPubShareDemand],[ViewPubShareDemand],[ViewCrossPubShareCustomer],[ViewPubShareCustomer],[viewtrace],CanDeletePicture,CanUploadPicture,CanPublishHouse,getdate() "
                       + "from Struct_UserDepartRelation where userid='{3}' and DepartId<>'{4}';",hrinfo.UserId,hrinfo.UserCode,hrinfo.UserName,aimuserid,hrinfo.BelongDepartId);
                
            }

            strSql += "update Struct_UserDepartRelation set IsControl='True' where IsBelong='True';";
            bool flag = Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.ExecuteSQL(strSql);            

            System.Text.StringBuilder str = new System.Text.StringBuilder();

            if (flag)
            {
                AddLog("" + CurrentUserInfo.UserName + "添加业务设定",
                    OperationType.OperationTypeComboList()["OprType_AddEMPSetting"].ToString()); 
                
                context.Response.Write(string.Format("{{success:'1',msg:'添加成功！',data:''}}"));                
            }
            else
            {
                context.Response.Write(string.Format("{{success:'0',msg:'没有可添加的人员',data:''}}"));
            }
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message));
        }
    }

    //删除人员
    private void delUser(HttpContext context)
    {
        try
        {
            string userid = "";
            if (!string.IsNullOrEmpty(context.Request.Params["userid"]))
            {
                userid = context.Request.Params["userid"];
            }
            string strSql = string.Format("delete Struct_UserDepartRelation where recordid='{0}'", userid);

            bool flag = Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.ExecuteSQL(strSql);
            if (flag)
            {
                AddLog("" + CurrentUserInfo.UserName + "删除业务设定",
                    OperationType.OperationTypeComboList()["OprType_DelEMPSetting"].ToString()); 
                
                context.Response.Write(string.Format("{{success:'1',msg:'删除成功！',data:{{isDelUser:true}}}}"));
            }
            else
                context.Response.Write(string.Format("{{success:'0',msg:'参数传递错误，请确认！',data:''}}"));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message));
        }
    }

    //名称验证
    private void NameCheck(HttpContext context)
    {
        try
        {
            //子类型（城市、公司、商圈、门店）
            string stype = "";
            string strwhere = "";
            //节点名字
            string name = "";
            //父节点ID
            string parentid = "";

            if (!string.IsNullOrEmpty(context.Request.QueryString["type"]))
            {
                stype = context.Request.QueryString["type"];
            }
            switch (stype)
            {

                case "100":
                    if (!string.IsNullOrEmpty(context.Request.QueryString["name"]))
                    {
                        name = context.Request.QueryString["name"];
                    }
                    if (!string.IsNullOrEmpty(context.Request.QueryString["fatherid"]))
                    {
                        parentid = context.Request.QueryString["fatherid"];
                    }
                    if (context.Request.QueryString["submitop"] != "add")
                        strwhere = String.Format("DepartName='{0}' and DepartProperty=100 and DepartId<>'{1}'", name,parentid);
                    else
                        strwhere = String.Format("DepartName='{0}' and DepartProperty=100", name);
                    break;
                case "200":
                    if (!string.IsNullOrEmpty(context.Request.QueryString["name"]))
                    {
                        name = context.Request.QueryString["name"];
                    } if (!string.IsNullOrEmpty(context.Request.QueryString["fatherid"]))
                    {
                        parentid = context.Request.QueryString["fatherid"];
                    }
                    if (context.Request.QueryString["submitop"] != "add")
                        strwhere = String.Format("DepartName='{0}' and DepartProperty=200 and CityId=(select CityId from Hr_DepartmentInfo where DepartId='{1}') and DepartId<>'{1}'", name, parentid);
                    else
                        strwhere = String.Format("DepartName='{0}' and DepartProperty=200 and CityId=(select CityId from Hr_DepartmentInfo where DepartId='{1}')", name, parentid);
                    break;
                case "300":
                    if (!string.IsNullOrEmpty(context.Request.QueryString["name"]))
                    {
                        name = context.Request.QueryString["name"];
                    }
                    if (!string.IsNullOrEmpty(context.Request.QueryString["fatherid"]))
                    {
                        parentid = context.Request.QueryString["fatherid"];
                    }
                    if (context.Request.QueryString["submitop"] != "add")
                        strwhere = String.Format("DepartName='{0}' and DepartProperty={1} and CompanyId=(select CompanyId from Hr_DepartmentInfo where DepartId='{2}') and DepartId<>'{2}'", name, stype, parentid);
                    else
                        strwhere = String.Format("DepartName='{0}' and DepartProperty={1} and CompanyId=(select CompanyId from Hr_DepartmentInfo where DepartId='{2}')", name, stype, parentid);
                    break;
                case "400":
                    goto case "300";
                case "500":
                    goto case "300";
                case "600":
                    goto case "300";
            }

            DataSet ds = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetList(strwhere);
            if (ds.Tables[0].Rows.Count > 0)
                context.Response.Write("{success:1,msg:'',data:{exist:true}}");
            else
                context.Response.Write("{success:1,msg:'',data:{exist:false}}");
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message));
        }
    }

    //编号验证
    private void CodeCheck(HttpContext context)
    {
        try
        {
            //子类型（城市、公司、商圈、门店）
            string stype = "";
            string strwhere = "";
            //节点名字
            string code = "";
            //父节点ID
            string parentid = "";

            if (!string.IsNullOrEmpty(context.Request.QueryString["type"]))
            {
                stype = context.Request.QueryString["type"];
            }
            switch (stype)
            {
            case "100":
                if (!string.IsNullOrEmpty(context.Request.QueryString["name"]))
                {
                    code = context.Request.QueryString["name"];
                }
                strwhere = String.Format("DepartCode='{0}' and DepartProperty=100", code);
                break;
            case "200":
                if (!string.IsNullOrEmpty(context.Request.QueryString["name"]))
                {
                    code = context.Request.QueryString["name"];
                } if (!string.IsNullOrEmpty(context.Request.QueryString["fatherid"]))
                {
                    parentid = context.Request.QueryString["fatherid"];
                }
                strwhere = String.Format("DepartCode='{0}' and DepartProperty=200 and CityId='{1}'", code, parentid);
                break;
            case "300":
                if (!string.IsNullOrEmpty(context.Request.QueryString["name"]))
                {
                    code = context.Request.QueryString["name"];
                }
                if (!string.IsNullOrEmpty(context.Request.QueryString["fatherid"]))
                {
                    parentid = context.Request.QueryString["fatherid"];
                }
                strwhere = String.Format("DepartCode='{0}' and DepartProperty={1} and CompanyId=(select CompanyId from Hr_DepartmentInfo where DepartId='{2}')", code, stype, parentid);
                break;
             case "400":
                    goto case "300";
                case "500":
                    goto case "300";
                case "600":
                    goto case "300";
            }

            DataSet ds = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetList(strwhere);
            if (ds.Tables[0].Rows.Count > 0)
                context.Response.Write("{success:1,msg:'',data:{exist:true}}");
            else
                context.Response.Write("{success:1,msg:'',data:{exist:false}}");
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message));
        }
    }


}